package com.hair.logy.core.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hair.logy.core.dao.HairCardMapper;
import com.hair.logy.core.model.HairCard;
import com.hair.logy.core.model.HairCardInfo;
import com.hair.logy.core.utils.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.*;

import static com.hair.logy.core.utils.Constant.AMOUNT;
import static com.hair.logy.core.utils.Constant.BASE_URL;
import static com.hair.logy.core.utils.QRcodeUtil.generateQrCodes;

@Component
public class HairCardServiceImpl implements HairCardService {

     @Autowired
     private HairCardMapper  hairCardMapper;
    @Override
    public void generateQrcode(Integer number,HttpServletResponse response) {
        // 生成指定数目二维码 可以生成二维码的数量
        List<String> constants=new ArrayList<>();
        List<HairCard>  hairCards=new ArrayList<>();
        Map<String ,String> constantsMaps=new HashMap<>();
        HairCard  nextHairCard= hairCardMapper.findNextHairCard();
        long  startNo=1;
        if(nextHairCard!=null){
            long  temp=nextHairCard.getId()+1;
            startNo=temp;
        }
        for (int i = 0; i <number ; i++) {
            String   cardNo="";
            if(startNo<1000){
                if(startNo<10&&startNo>0 ){
                    cardNo= "N0.888000"+startNo;
                }
                else if(startNo<100&&startNo>=10){
                    cardNo= "N0.88800"+startNo;
                }else if(startNo<1000&&startNo>=100)
                cardNo= "N0.8880"+startNo;
            }else{
           cardNo= "N0.888"+startNo;}
            HairCard  hairCard=new HairCard();
            hairCard.setCardNo(cardNo);
            hairCard.setJumpUrl(BASE_URL+"?cardNo="+cardNo+"&amount="+AMOUNT);
            hairCard.setCardStatus(0);
            hairCard.setAmount(AMOUNT);
            hairCards.add(hairCard);
            System.out.println(BASE_URL+"?cardNo="+cardNo+"&amount="+AMOUNT);
            constants.add(BASE_URL+"?cardNo="+cardNo+"&amount="+AMOUNT);
            constantsMaps.put(BASE_URL+"?cardNo="+cardNo+"&amount="+AMOUNT,cardNo);
            startNo++;
        }
        List<File>  files = generateQrCodes(constants,constantsMaps, "png");
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition","attachment;filename="+"qrCode.zip");
        response.setCharacterEncoding("UTF-8");
        OutputStream os = null;
        InputStream inputStream=null;
        try {
            os=response.getOutputStream();
            FileZip.toZip("qrCode.zip",files,os);
           // 处理完毕以后删除文件
            for (int i = 0; i <files.size() ; i++) {
               File  file=files.get(i);
                file.delete();
            }
            hairCardMapper.batchInsert(hairCards);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if(os != null) {
                    os.flush();
                    os.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public HairCardInfo listHairCard(Integer start, Integer end, String cardNo) {
        HairCardInfo  hairCardInfo=new HairCardInfo();
         String   cardNoStr=null;
        if(cardNo!=null && !"".equals(cardNo)){
            cardNoStr="%" + cardNo + "%";
        }

      List<HairCard>  hairCards=  hairCardMapper.listHairCardByCardNoAndPageSize(start,end,cardNoStr) ;
        Integer total=hairCardMapper.countHairCardByCardNoAndPageSize(cardNoStr) ;
        hairCardInfo.setHairCardList(hairCards);
        hairCardInfo.setTotal(total);
        return  hairCardInfo;
    }

    @Override
    public void register(HairCard hairCard) throws BusinessException {
     // 查找是否存在
      HairCard hairCards= hairCardMapper.findHairCardByCardNo(hairCard.getCardNo());
      if(hairCards==null) {
          throw new BusinessException(-1, "未找到卡号， 请检查扫描的二维码是否正确");
      }
      if(hairCards.getCardStatus()==1||hairCards.getCardStatus()==2){
          throw new BusinessException(-1, "当前二维码已经使用， 请选择最新的卡劵使用");
      }
      hairCards.setCardStatus(1);
      hairCards.setIphoneNo(hairCard.getIphoneNo());
      hairCards.setUserName(hairCard.getUserName());
      // 记录时间
      hairCards.setApplyTime(new Date());
      hairCardMapper.updateById(hairCards);
    }

    @Override
    public HairCard activateHairCard(Long id) throws BusinessException {
        HairCard hairCards=    hairCardMapper.selectById(id);
        if(hairCards==null){
            throw new BusinessException(-1, "未找到需要激活的卡劵，请刷新页面后重试");
        }
        if(hairCards.getCardStatus()==0){
            throw new BusinessException(-1, "该卡劵还未被用户申请，不能激活");
        }
        if(hairCards.getCardStatus()==2){
            throw new BusinessException(-1, "该卡劵已经激活不需要重新激活");
        }
        hairCards.setCardStatus(2);
        hairCards.setActivateTime(new Date());
        hairCardMapper.updateById(hairCards);
        return hairCards;
    }

    @Override
    public void downLoadHairFile(String cardNo, HttpServletResponse response) {
        // 生成指定数目二维码 可以生成二维码的数量
        List<String> constants=new ArrayList<>();
        List<HairCard>  hairCards=new ArrayList<>();
        Map<String ,String> constantsMaps=new HashMap<>();
        HairCard  nextHairCard= hairCardMapper.findHairCardByCardNo(cardNo);
        if(nextHairCard==null){

        }
        constants.add(nextHairCard.getJumpUrl());
        constantsMaps.put(nextHairCard.getJumpUrl(),nextHairCard.getCardNo());
        List<File>  files = generateQrCodes(constants,constantsMaps, "png");
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition","attachment;filename="+"qrCode.zip");
        response.setCharacterEncoding("UTF-8");
        OutputStream os = null;
        InputStream inputStream=null;
        try {
            os=response.getOutputStream();
            FileZip.toZip(nextHairCard.getCardNo()+".zip",files,os);
            // 处理完毕以后删除文件
            for (int i = 0; i <files.size() ; i++) {
                File  file=files.get(i);
                file.delete();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if(os != null) {
                    os.flush();
                    os.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
